package com.mdsoft.dao.properties;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import com.mdsoft.dao.AdminDao;
import com.mdsoft.po.Admin;

public class PropertiesAdminDao implements AdminDao{

	private static final String USERNAME = "username";
	private static final String PASSWORD = "password";
	private static final String LOGINCOUNT = "logincount";
	private static final int ID = 1;
	
	private Properties properties;
	private String fileName = "admin.properties";
	
	@Override
	public void update(Admin admin) {
		load();
		properties.setProperty(USERNAME, admin.getUsername());
		properties.setProperty(PASSWORD, admin.getPassword());
		properties.setProperty(LOGINCOUNT, admin.getLoginCount() + "");
		save();
	}

	@Override
	public Admin get(int id) {
		if (id == ID) {
			load();
			Admin admin = new Admin();
			admin.setId(ID);
			admin.setUsername(properties.getProperty(USERNAME));
			admin.setPassword(properties.getProperty(PASSWORD));
			admin.setLoginCount(Integer.parseInt(properties.getProperty(LOGINCOUNT)));
			
			return admin;
		}
		return null;
	}

	@Override
	public Admin login(String username, String password) {
		Admin admin = get(ID);
		if (admin != null) {
			if (admin.getUsername().equals(username) && admin.getPassword().equals(password)) {
				admin.setLoginCount(admin.getLoginCount() + 1);
				update(admin);
				return admin;
			}
		}
		
		return null;
	}
	

	private void load() {
		properties = new Properties();
		try {
			properties.load(new FileInputStream(fileName));
		} catch (FileNotFoundException e) {
			File file = new File(fileName);
			try {
				file.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			properties.setProperty(USERNAME, "teacher");
			properties.setProperty(PASSWORD, "123456");
			properties.setProperty(LOGINCOUNT, "0");
			
			
			save();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void save() {
		try {
			properties.store(new FileOutputStream(fileName), null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
}
